package com.xie.wechat;






import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FragmentFour extends Fragment  {
    private SharedPreferences sharedPreferences = null;
    private String loginUrl2 = "http://10.23.34.211:3000/api/user/account/info/";

    private TextView UserName;
    private ImageView UserImage;

    private Button btn_logout;//退出按钮
    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public final static String BASE_URL="http://10.23.34.211:3000/";
    public final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)// 设置读取超时时间
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)// 设置写的超时时间
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)// 设置连接超时时间
            .build();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

        View view = inflater.inflate(R.layout.fragment_fragment_four, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(); // 初始化数据
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getInfo();

    }

    private void initView() {

        UserName = (TextView) getActivity().findViewById(R.id.UserName);
        btn_logout = (Button) getActivity().findViewById(R.id.logout);
        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
    }
    private  void  logout(){
        SharedPreferences userSettings = getActivity().getSharedPreferences("mytoken", MODE_PRIVATE);
        SharedPreferences.Editor editor = userSettings.edit();
        editor.remove("token");
        editor.commit();
        // Intent 去设置要跳转的页面
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        // 进行跳转
        startActivity(intent);

    }
    private void getInfo() {
        String token = "";
        sharedPreferences = getActivity().getSharedPreferences("mytoken", MODE_PRIVATE);

        token = sharedPreferences.getString("token", "");
        Request request = new Request.Builder()
                .url(BASE_URL + "api/user/account/info/")

                //.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0ZWE0Y2IyMjdkYTk0ZjU2YmU3ZTM3OGM3NzQ3Y2NkNCIsInN1YiI6IjEiLCJpc3MiOiJzZyIsImlhdCI6MTY2OTA4NTU0NywiZXhwIjoxNjcwMjk1MTQ3fQ.iL4DD6rZkS6Gg5OGhznCkXnGzjo8LEcb1RyS6g-WJGM")
                //.addHeader("Content-Type", "application/json;charset=UTF-8")
                //.addHeader("Origin","*")
                //.addHeader("Access-Control-Request-Headers","*")
                .addHeader("Authorization", "Bearer " + token)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("111111 post 请求失败 ======", "e.getMessage()" + e.getMessage());
                Log.d("111111 post 请求失败 ======", "e.request()" + call.request());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功返回结果
                // 如果希望返回的是字符串

                final String responseData = new String(response.body().string());

                // 注意，此时的线程不是ui线程，
                // 如果此时我们要用返回的数据进行ui更新，操作控件，就要使用相关方法

                Log.d("111111 post 请求成功 ===", "responseData >>" + responseData);

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        LoginBean bean = new Gson().fromJson(responseData, LoginBean.class);

                        String username1= bean.getUsername();
                        String photo = bean.getPhoto();
                        Integer userid = bean.getUserId();

                        // 存Token
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myinfo", MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putInt("userid",userid);
                        editor.putString("username", username1);
                        editor.putString("photo", photo);
                        editor.commit();
                        UserName.setText(username1);

                    }
                });

            }
        });
    }
//    //第一种方法
//    public Bitmap getHttpBitmap(String data)
//    {
//        Bitmap bitmap = null;
//        try
//        {
//            //初始化一个URL对象
//            URL url = new URL(data);
//            //获得HTTPConnection网络连接对象
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.setConnectTimeout(5*1000);
//            connection.setDoInput(true);
//            connection.connect();
//            //得到输入流
//            InputStream is = connection.getInputStream();
//            Log.i("TAG", "*********inputstream**"+is);
//            bitmap = BitmapFactory.decodeStream(is);
//            Log.i("TAG", "*********bitmap****"+bitmap);
//            //关闭输入流
//            is.close();
//            //关闭连接
//            connection.disconnect();
//        } catch (Exception e)
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        return bitmap;
//    }


}
